package cn.kooki.app.duobao.ui.Activity.User;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import java.lang.ref.WeakReference;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseNavActivity;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.Index.NoticeItem;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.base.BaseResponse;
import cn.kooki.app.duobao.data.bus.UserRefrshEvent;
import cn.kooki.app.duobao.ui.widget.ClearEditText;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.StringUtils;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2016/1/7.
 */
public class BindActivity extends BaseNavActivity implements View.OnClickListener {
    @Bind(R.id.et_mobile)
    ClearEditText etMobile;
    @Bind(R.id.et_captcha)
    ClearEditText etCaptcha;
    @Bind(R.id.bt_captcha)
    Button btCaptcha;
    private AlertDialog.Builder builder;
    private UserInfo userinfo;
    private int mincount = 90;

    @Override
    public void setLayoutContainerView() {
        setContainerView(R.layout.activity_profile_mobile);
        ButterKnife.bind(this);
    }

    @Override
    protected void afterView() {
        setTitle("绑定手机");
        topBack.setOnClickListener(this);
        actionEdit.setOnClickListener(this);
        actionEdit.setText(R.string.save);
        actionEdit.setVisibility(View.VISIBLE);
        btCaptcha.setOnClickListener(this);
        userinfo = SharePreferencesUtils.getUserinfo(this);
        showtips();
    }

    private PlayHandler playHandler = new PlayHandler(this);


    private static class PlayHandler extends Handler {

        private final WeakReference<BindActivity> mActivity;

        public PlayHandler(BindActivity activity) {
            mActivity = new WeakReference<BindActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {

            BindActivity bindActivity = mActivity.get();
            if (bindActivity == null) {
                return;
            }
            if (msg.what == 0) {
                int mincount = bindActivity.mincount--;
                bindActivity.btCaptcha.setText(mincount + "秒后重新发送");
                if (mincount <= 0) {
                    bindActivity.mincount = 90;
                    bindActivity.playHandler.sendEmptyMessageDelayed(1, 1000);
                } else {
                    bindActivity.playHandler.sendEmptyMessageDelayed(0, 1000);
                }
            } else if (msg.what == 1) {
                bindActivity.btCaptcha.setEnabled(true);
                bindActivity.btCaptcha.setText(R.string.register_resend);
            }
        }
    }


    private void showtips() {
        boolean isshowtips = SharePreferencesUtils.getBoolean(this, userinfo.getUid(), "isshowtips");
        if (!isshowtips) {
            new AlertDialog.Builder(this).setMessage(getString(R.string.bind_tips))
                    .setPositiveButton("确定", null).setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    SharePreferencesUtils.putBoolean(BindActivity.this, userinfo.getUid(), "isshowtips", true);
                }
            }).show();
        }
    }

    @Override
    public void onClick(View v) {
        if (v == topBack) {
            if (builder == null) {
                builder = new AlertDialog.Builder(this);
                builder.setMessage(getString(R.string.no_bind_tips)).setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setPositiveButton("取消", null).setCancelable(false);
            }
            builder.show();
        }
        if (v == actionEdit) {
            bindphone();
        }
        if (v == btCaptcha) {
            if (checkform(false)) {
                btCaptcha.setEnabled(false);
                playHandler.sendEmptyMessage(0);

                MainFactory.getApiInstance().getcode(etMobile.getText().toString(), new Callback<BaseResponse>() {
                    @Override
                    public void success(BaseResponse baseResponse, Response response) {

                    }

                    @Override
                    public void failure(RetrofitError error) {

                    }
                });
            }
        }

    }

    private void bindphone() {

        if (checkform(false)) {
            showLoading("正在绑定");
            MainFactory.getApiInstance().binphone(userinfo.getUid(), etCaptcha.getText().toString(), etMobile.getText().toString(), new Callback<BaseResponse>() {
                @Override
                public void success(BaseResponse baseResponse, Response response) {
                    dismissDialog();
                    if (baseResponse.getStatus() == 0) {
                        showToastMessage("绑定成功");
                        userinfo.setMobile(etMobile.getText().toString());
                        SharePreferencesUtils.putUserinfo(BindActivity.this, userinfo);
                        EventBus.getDefault().post(new UserRefrshEvent());
                        intent(DuobaoBonusAcitivity.class);
                        finish();
                    } else {
                        showToastMessage(baseResponse.getMsg());
                    }
                }

                @Override
                public void failure(RetrofitError error) {
                    dismissDialog();
                    showToastMessage("网络错误");
                }
            });
        }
    }

    private boolean checkform(boolean isonlyMobile) {

        if (!StringUtils.isMobile(etMobile.getText().toString())) {
            showToastMessage("请输入手机号码");
            return false;
        }
        if (!TextUtils.isEmpty(etCaptcha.getText().toString()) && isonlyMobile) {
            showToastMessage("请输入验证码");
            return false;
        }

        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        builder = null;
    }
}
